package com.daxt.controller.webuse;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import com.daxt.common.annotations.LoginAuth;
import com.daxt.common.annotations.LoginUser;
import com.daxt.common.exception.BaseException;
import com.daxt.common.util.DateUtil;
import com.daxt.common.util.EkpHttpWsUtil;
import com.daxt.mapper.sys.*;
import com.daxt.mapper.use.ActRuTaskMapper;
import com.daxt.mapper.use.UseBorrowFondsRecordMapper;
import com.daxt.model.dic.BehaveLogType;
import com.daxt.model.dic.VersionsMarkType;
import com.daxt.model.dto.BorrowDto;
import com.daxt.model.dto.EkpReplaceDisposeDto;
import com.daxt.model.service.archives.vo.ArchivesBehaveLog;
import com.daxt.model.service.archives.vo.ArchivesFonds;
import com.daxt.model.service.base.vo.*;
import com.daxt.model.service.use.vo.*;
import com.daxt.service.*;
import com.daxt.service.impl.ProcessCustomServiceImpl;
import com.daxt.utils.ArchivesUtil;
import com.daxt.utils.BaseUtil;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricDetail;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableUpdate;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.base.common.util.UserInfoUtil;
import com.daxt.common.result.PageInfo;
import com.daxt.common.result.PageUtil;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.common.util.Md5Util;
import com.daxt.mapper.archives.ArchivesDocMapper;
import com.daxt.mapper.use.UseBorrowRecordMapper;
import com.daxt.mapper.use.UseUserRecordLogMapper;
import com.daxt.model.service.archives.result.ArchivesDetails;
import com.daxt.model.service.archives.vo.ArchivesDoc;
import com.daxt.model.service.base.param.ChangePassword;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.utils.LocalDateTimeUtil;
import com.daxt.utils.MyDateUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "档案利用")
@RestController
@RequestMapping("/web")
public class UserUseController {

    @Autowired
    private ArchivesFondsMapper archivesFondsMapper;
    @Autowired
    private UseBorrowRecordMapper useBorrowRecordMapper;
    @Autowired
    private UseBorrowFondsRecordMapper useBorrowFondsRecordMapper;
    @Autowired
    private UseUserRecordLogMapper useUserRecordLogMapper;
    @Autowired
    private ArchivesDocMapper archivesDocMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private DocService docService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private EkpRecordMapper ekpRecordMapper;
    @Autowired
    private UserDeptMapper userDeptMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private UserPostMapper userPostMapper;
    @Autowired
    private UserService userService;

    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    IdentityService identityService;
    @Autowired
    HistoryService histiryService;
    @Autowired
    BaseTaskMapper baseTaskMapper;
    @Autowired
    UseBorrowService useBorrowService;
    @Autowired
    ProcessCustomService processCustomService;
    @Autowired
    ProcessDetailsMapper processDetailsMapper;
    @Autowired
    private ActRuTaskMapper actRuTaskMapper;
    @Autowired
    private ArchivesAcceptService acceptService;
    @Autowired
    private ArchivesBehaveLogService archivesBehaveLogService;


    @ApiOperation(value = "个人信息", notes = "")
    @GetMapping("/userInfo")
    public Result<UserInfo> userInfo(HttpServletRequest request) {
        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        //BaseUser selectById = userMapper.selectById(loginInfo.getId());
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", loginInfo);
    }

    @ApiOperation(value = "个人信息修改", notes = "")
    @PostMapping("/editUserInfo")
    public Result<String> editInfo(@RequestBody BaseUser baseUser, HttpServletRequest request) {
        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        BaseUser u = new BaseUser();
        u.setRealName(baseUser.getRealName());
        u.setMobile(baseUser.getMobile());
        u.setEmail(baseUser.getEmail());
        baseUser.setId(loginInfo.getId());
        int updateById = userMapper.updateById(baseUser);
        if (updateById > 0) {
            loginInfo.setEmail(baseUser.getEmail());
            loginInfo.setRealName(baseUser.getRealName());
            loginInfo.setMobile(baseUser.getMobile());
            UserInfoUtil.updateLogInfo(loginInfo, redisUtil, request);
        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }

    @ApiOperation(value = "修改密码", notes = "")
    @PutMapping("/changePassword")
    public Result<String> changePassword(@RequestBody ChangePassword changePassword, HttpServletRequest request) {

        String pattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,20}$";

        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        if (loginInfo == null) {
            return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
        }
        if (!Md5Util.hash(changePassword.getOldPassword()).equals(loginInfo.getPassword())) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "原密码不正确", null);
        } else if (!changePassword.getAgainPassword().equals(changePassword.getNewPassword())) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "两次密码不一致", null);
        } else {
            String newPassword=changePassword.getNewPassword();
            if(!newPassword.matches(pattern)){
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "密码长度不能小于8位,并且包含大小写字母数字特殊字符组合", null);
            }

            BaseUser entity = new BaseUser();
            entity.setId(loginInfo.getId());
            entity.setPassword(com.daxt.common.util.Md5Util.hash(changePassword.getAgainPassword()));
            int rows = userMapper.updateById(entity);
            return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), rows > 0 ? "修改成功" : "修改失败", null);
        }
    }

    @ApiOperation(value = "个人审批按钮权限", notes = "")
    @GetMapping("/userPost")
    public Result<String> userPost(HttpServletRequest request) {
        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        QueryWrapper<UserPost> wrapper=new QueryWrapper<>();
        wrapper.eq("id",loginInfo.getId());
        int count = userPostMapper.selectCount(wrapper);
        String data="false";
        if(count>0){
            data="true";
        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "",data );
    }

    @ApiOperation(value = "个人借阅/审批列表", notes = "")
    @GetMapping("/borrow")
    public Result<PageInfo<UseBorrowRecord>> identList(@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                                       @ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                                       @ApiParam("题名") @RequestParam(value = "title", required = false) String title,
                                                       @ApiParam("借阅开始时间") @RequestParam(value = "startTime", required = false) String startTime,
                                                       @ApiParam("借阅结束时间") @RequestParam(value = "endTime", required = false) String endTime,
//			@ApiParam("分类号") @RequestParam(value = "classNum", required = false)String classNum,
//			@ApiParam("全宗号") @RequestParam(value = "fondsId", required = false)String fondsId,
//			@ApiParam("档案类型") @RequestParam(value = "typeNmu", required = false)String typeNmu,
                                                       @ApiParam("本公司/总公司标识, 1/0") @RequestParam(value = "flag", required = false) String flag,
                                                       HttpServletRequest request,
                                                       @ApiParam("1代表我的借阅，2代表我的审批") @RequestParam(value = "type", required = false) String type) {
        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);

        Page<UseBorrowRecord> page = new Page<>(pageNum == null ? 0 : pageNum, pageSize == null ? 10 : pageSize);
        QueryWrapper<UseBorrowRecord> queryWrapper = new QueryWrapper<>();

        if("2".equals(type)){
            QueryWrapper<ProcessDetails> processQueryWrapper=new QueryWrapper<>();
            processQueryWrapper.eq("approver",loginInfo.getUsername());
            List<ProcessDetails> proList=processDetailsMapper.selectList(processQueryWrapper);
            List<String> executionIds  =new ArrayList<>();
            for (int i=0;i<proList.size();i++){
                executionIds.add(proList.get(i).getProcessId());
            }
        }


        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("title", title);
        }

//		if(!StringUtils.isEmpty(typeNmu)&&!StringUtils.isEmpty(fondsId)) {
//			queryWrapper.eq("typeNmu", typeNmu);
//			queryWrapper.eq("fondsId", fondsId);
//			if(!StringUtils.isEmpty(classNum)) {
//				queryWrapper.eq("classNum", classNum);
//			}
//		}

        if (!StringUtils.isEmpty(flag) && flag.equals("1")) {
            queryWrapper.eq("fondsId", loginInfo.getFondsId());
        }
        if (!StringUtils.isEmpty(flag) && flag.equals("0")) {
            queryWrapper.eq("fondsId", "90000");
        }


        if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
            queryWrapper.gt("startTime", startTime);
            queryWrapper.lt("endTime", endTime);

        }
        if(!"2".equals(type)){
            queryWrapper.eq("userId", loginInfo.getId());
        }
        IPage<UseBorrowRecord> info = useBorrowRecordMapper.selectPage(page, queryWrapper);
        useBorrowService.buildArchives(info.getRecords());


        PageInfo<UseBorrowRecord> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", data);
    }

    @ApiOperation(value = "个人审批数量", notes = "")
    @GetMapping("/borrow/count")
    public Result<String> identCount(HttpServletRequest request){

        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        QueryWrapper<UseBorrowRecord> queryWrapper = new QueryWrapper<>();

        QueryWrapper<ActRuTask> taskQueryWrapper=new QueryWrapper<>();
        taskQueryWrapper.eq("ASSIGNEE_",loginInfo.getUsername());
        List<ActRuTask> ActRuTasks = actRuTaskMapper.selectList(taskQueryWrapper);
        List<String> executionIds  =new ArrayList<>();
        for (int i=0;i<ActRuTasks.size();i++){
            executionIds.add(ActRuTasks.get(i).getExecutionId());
        }
        queryWrapper.in(executionIds.size()>0,"processId",executionIds);
        queryWrapper.eq("fondsId",loginInfo.getFondsId());
        Integer count =0;
        if(executionIds.size()>0){
            count=useBorrowRecordMapper.selectCount(queryWrapper);
        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", count.toString());
    }


    @ApiOperation(value = "个人借阅撤销", notes = "")
    @GetMapping("/borrow/return/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> identList(@PathVariable("id") String id, HttpServletRequest request) {
        UseBorrowRecord bean = useBorrowRecordMapper.selectById(id);
        bean.setState("4");
        useBorrowRecordMapper.updateById(bean);
        try {
            if (null != bean) {
                Task task = taskService.createTaskQuery().processInstanceId(bean.getProcessId()).singleResult();


                if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
                    String taskKey = task.getTaskDefinitionKey();
                    String assignee = task.getAssignee();
                    QueryWrapper<Post> postQueryWrapper=new QueryWrapper<>();
                    switch (taskKey){
                        case "deptLeaderAudit":
                            postQueryWrapper.eq("code","deptLeader");
                            break;
                        case "officeLeaderAudit":
                            postQueryWrapper.eq("code","officeLeader");
                            break;
                        case "archivistLeaderAudit":
                            postQueryWrapper.eq("code","archivistLeader");
                            break;
                    }
                    Post post= postMapper.selectOne(postQueryWrapper);
                    acceptService.updateFlow(bean.getProcessId(),post.getId().toString(),post.getName(),assignee,DateUtil.getCurrentTime(),"3");
                }
                processCustomService.endProcess(task.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(ResultCode.RESULT_ERROR.getCode(), "流程停止失败");
        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", "");
    }

    @ApiOperation(value = "下载文件验证", notes = "")
    @GetMapping("/borrow/validateDown/{fileId}")
    public Result<Integer> validateDown(@PathVariable("fileId") String fileId, HttpServletRequest request) {
        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        QueryWrapper<UseBorrowRecord> queryWrapper = new QueryWrapper<UseBorrowRecord>();
        queryWrapper.eq("fileId", fileId);
        queryWrapper.eq("authType", "1");
        queryWrapper.eq("userId", loginInfo.getId());
        List<UseBorrowRecord> list = useBorrowRecordMapper.selectList(queryWrapper);
        int i = 0;
        if (list != null && list.size() > 0) {
            i = 1;
        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", i);
    }


//    @ApiOperation(value = "续借", notes = "")
//    @PostMapping("/borrow/renew")
//    public Result<String> identList(@ApiIgnore @LoginUser UserInfo loginUser,@RequestBody UseBorrowRecord useBorrowRecord,
//                                    HttpServletRequest request) {
//        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
//
//        if(useBorrowRecord.getState().equals("1") || useBorrowRecord.getState().equals("3")){
//            useBorrowRecord.setState("0");
////            useBorrowRecordMapper.updateById(useBorrowRecord);
//        }
//
////        useBorrowRecord.setUserId(loginInfo.getId());
////        useBorrowRecord.setCreateBy(loginInfo.getRealName());
//
//
//        //启动流程
//        useBorrowService.startBorrow(useBorrowRecord);
//
//
//        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
//    }
//    @ApiOperation(value = "续借", notes = "")
//    @PostMapping("/borrow/renew")
//    public Result<String> identList(@RequestBody UseBorrowRecord useBorrowRecord,
//                                    HttpServletRequest request) {
//        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
//
//        if(useBorrowRecord.getState().equals("1") || useBorrowRecord.getState().equals("3")){
//            useBorrowRecord.setState("0");
//        }
//
//        useBorrowRecord.setUserId(loginInfo.getId());
//        useBorrowRecord.setCreateBy(loginInfo.getRealName());
//        useBorrowRecordMapper.updateById(useBorrowRecord);
//        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
//    }


//    @ApiOperation(value = "借阅", notes = "")
//    @PostMapping("/borrow/submit")
//    public Result<String> submit(@RequestBody UseBorrowRecord useBorrowRecord,
//                                 HttpServletRequest request) {
//        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
//        useBorrowRecord.setUserId(loginInfo.getId());
//        useBorrowRecord.setCreateBy(loginInfo.getRealName());
//
//        useBorrowRecord.setCreateTime(DateUtil.getCurrentTime());
//        useBorrowRecord.setState("0");
//        ArchivesDoc doc = archivesDocMapper.selectById(useBorrowRecord.getFileId());
//        useBorrowRecord.setFondsId(doc.getFondsId());
//        useBorrowRecord.setTypeNum(doc.getTypeNum());
//        useBorrowRecord.setClassNum(doc.getClassNum());
//        useBorrowRecord.setTitle(doc.getTitle());
//
//
//        // 获取日期
//        Date date1 = MyDateUtil.parseDate(useBorrowRecord.getStartTime(), "yyyy-MM-dd");
//        Date date2 = MyDateUtil.parseDate(useBorrowRecord.getEndTime(), "yyyy-MM-dd");
//
//        // 获取相差的天数
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(date1);
//        long timeInMillis1 = calendar.getTimeInMillis();
//        calendar.setTime(date2);
//        long timeInMillis2 = calendar.getTimeInMillis();
//
//        long betweenDays = (timeInMillis2 - timeInMillis1) / (1000L * 3600L * 24L);
//        useBorrowRecord.setBDays(new Long(betweenDays).toString());
//        useBorrowRecordMapper.insert(useBorrowRecord);
//        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
//    }


    @ApiOperation(value = "借阅申请", notes = "")
    @PostMapping("/borrow/submit")
    @LoginAuth()
    @Transactional(rollbackFor = Exception.class)
    public Result<String> submit(@ApiIgnore @LoginUser UserInfo loginUser, @RequestBody UseBorrowRecord useBorrowApply, HttpServletRequest request) {


        //纸质借阅
        if ((useBorrowApply.getAuthType().equals("3") || useBorrowApply.getAuthType().equals("2"))) {
            int bNum = useBorrowService.borrowNumByAuthTypeAndDocId(useBorrowApply.getAuthType(), useBorrowApply.getFileId());
            if (bNum > 0) return ResultUtil.error("暂时不在档案库，需要耐心等待。。。");
        }


        QueryWrapper<UseBorrowRecord> ubaQw = new QueryWrapper<UseBorrowRecord>();
        ubaQw.eq("userId", loginUser.getId());
        ubaQw.eq("fileId", useBorrowApply.getFileId());
        ubaQw.and(Wrapper -> Wrapper.eq("state", "0").or().eq("state", "2"));
        //状态排除
        int i = useBorrowRecordMapper.selectCount(ubaQw);
        if (i > 0) return ResultUtil.error("已经存在借阅信息");


        useBorrowApply.setCreateTime(DateUtil.getCurrentTime());
        useBorrowApply.setState("0");
        ArchivesDoc doc = archivesDocMapper.selectById(useBorrowApply.getFileId());
        useBorrowApply.setFondsId(doc.getFondsId());
        useBorrowApply.setTypeNum(doc.getTypeNum());
        useBorrowApply.setClassNum(doc.getClassNum());
        useBorrowApply.setTitle(doc.getTitle());

        Map<String, Object> variables = new HashMap<String, Object>();

        useBorrowApply.setCreateTime(DateUtil.getCurrentTime());
        useBorrowApply.setCreateBy(loginUser.getUsername());
        useBorrowApply.setUserId(loginUser.getId());

        useBorrowRecordMapper.insert(useBorrowApply);

        //启动流程
        Result<String> s = useBorrowService.startBorrow(useBorrowApply);
        if (s.getCode().equals(ResultCode.RESULT_ERROR.getCode()))
            throw new BaseException(ResultCode.RESULT_ERROR.getCode(), s.getMsg());

        archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(useBorrowApply.getFileId().toString(), BehaveLogType.BORROW_APPLY.getKey(),BehaveLogType.BORROW_APPLY.getValue(),null),loginUser ,request);

        return ResultUtil.success();

    }


    @ApiOperation(value = "借阅 详情", notes = "")
    @GetMapping("/borrow/applyDetails/{applyId}")
    public Result<BorrowDto> applyDetails(@PathVariable("applyId") String applyId) {

        UseBorrowRecord bean = useBorrowRecordMapper.selectById(applyId);
        BorrowDto dto = new BorrowDto();
        List<ProcessDetails> pdsList = processDetailsMapper.selectList(new QueryWrapper<ProcessDetails>().eq("processId", bean.getProcessId()));

        for(int i=0;i<pdsList.size();i++){
            String approver= pdsList.get(i).getApprover();
            if(!StringUtils.isEmpty(approver)){
                QueryWrapper<BaseUser> userQueryWrapper=new QueryWrapper<>();
                userQueryWrapper.eq("username",approver);
                BaseUser baseUser = userMapper.selectOne(userQueryWrapper);
                pdsList.get(i).setApprover(baseUser.getRealName());
            }
        }

        dto.setProcessDetails(pdsList);

        if (null != bean) {
            BeanUtils.copyProperties(bean, dto);
            if(!StringUtils.isEmpty(dto.getCreateBy())){
                QueryWrapper<BaseUser> userQueryWrapper=new QueryWrapper<>();
                userQueryWrapper.eq("username",dto.getCreateBy());
                BaseUser baseUser = userMapper.selectOne(userQueryWrapper);
                dto.setCreateBy(baseUser.getRealName());
            }

            Task task = taskService.createTaskQuery().processInstanceId(bean.getProcessId()).singleResult();
//            List<HistoricDetail> flowDetailList = histiryService.createHistoricDetailQuery().processInstanceId(bean.getProcessId()).orderByTime().asc().list();
//            flowDetailList.forEach((HistoricDetail historicDetail)->{
//                HistoricVariableUpdate hd = (HistoricVariableUpdate) historicDetail;
//                String hdName = hd.getVariableName();
//
//                if(hdName.equals("${applyUserId}")){
//                    deptLeaderDto.setUserId(hd.getValue().toString());
//                    officeLeaderDto.setUserId(hd.getValue().toString());
//                    archivistLeaderDto.setUserId(hd.getValue().toString());
//                }
//                if(hdName.equals("${applyUserId}")){
//                    deptLeaderDto.setUserId(hd.getValue().toString());
//                }
//
//            });


//            List<HistoricTaskInstance> taskInfoList = histiryService.createHistoricTaskInstanceQuery().processInstanceId(bean.getProcessId()).list();
//            TaskInfo taskInfo = taskInfoList.get(taskInfoList.size()-1);
            if (null != task) {
                dto.setTaskId(task.getId());
                dto.setTaskName(task.getName());
                dto.setProcessinstanceId(task.getProcessInstanceId());
                dto.setProcessdefId(task.getProcessDefinitionId());
                dto.setTaskCreateTime(task.getCreateTime());

                String node = "";
                String taskKey = task.getTaskDefinitionKey();
                switch (taskKey) {
                    case "deptLeaderAudit":
                        node = "1";
                        break;
                    case "officeLeaderAudit":
                        node = "2";
                        break;
                    case "archivistLeaderAudit":
                        node = "3";
                        break;
                }
                dto.setFlowNode(node);

                dto.setApprover(task.getAssignee());


            }

            //增加档案基础信息
            ArchivesDoc ad = archivesDocMapper.selectById(dto.getFileId());
            dto.setBaseDocDto(ArchivesUtil.buildBaseDoc(ad));

            try {
                UserDept ud = userDeptMapper.selectOne(new QueryWrapper<UserDept>().eq("userId", bean.getUserId()));
                Dept d = deptMapper.selectById(ud.getDeptId());
                dto.setDeptName(d.getDeptName());
            } catch (Exception e) {
                //获取部门信息异常
            }


        }
        return ResultUtil.success(dto);
    }
//    @ApiOperation(value = "借阅 详情", notes = "")
//    @GetMapping("/borrow/applyDetails/{applyId}")
//    public Result<BorrowDto> applyDetails(@PathVariable("applyId") String applyId) {
//
//        UseBorrowRecord bean = useBorrowRecordMapper.selectById(applyId);
//        BorrowDto dto = new BorrowDto();
//        if (null != bean) {
//            BeanUtils.copyProperties(bean, dto);
//            Task task = taskService.createTaskQuery().processInstanceId(bean.getProcessId()).singleResult();
////            List<HistoricTaskInstance> taskInfoList = histiryService.createHistoricTaskInstanceQuery().processInstanceId(bean.getProcessId()).list();
////            TaskInfo taskInfo = taskInfoList.get(taskInfoList.size()-1);
//            if (null != task) {
//                dto.setTaskId(task.getId());
//                dto.setTaskName(task.getName());
//                dto.setProcessinstanceId(task.getProcessInstanceId());
//                dto.setProcessdefId(task.getProcessDefinitionId());
//                dto.setTaskCreateTime(task.getCreateTime());
//
//                String node = "";
//                String taskKey = task.getTaskDefinitionKey();
//                switch (taskKey) {
//                    case "deptLeaderAudit":
//                        node = "1";
//                        break;
//                    case "officeLeaderAudit":
//                        node = "2";
//                        break;
//                    case "archivistLeaderAudit":
//                        node = "3";
//                        break;
//                }
//                dto.setFlowNode(node);
//
//                dto.setApprover(task.getAssignee());
//
//
//            }
//
//            //增加档案基础信息
//            ArchivesDoc ad = archivesDocMapper.selectById(dto.getFileId());
//            dto.setBaseDocDto(ArchivesUtil.buildBaseDoc(ad));
//
//            try {
//                UserDept ud = userDeptMapper.selectOne(new QueryWrapper<UserDept>().eq("userId", bean.getUserId()));
//                Dept d = deptMapper.selectById(ud.getId());
//                dto.setDeptName(d.getDeptName());
//            } catch (Exception e) {
//                //获取部门信息异常
//            }
//
//
//        }
//        return ResultUtil.success(dto);
//    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "借阅审批", notes = "")
    @PostMapping("/borrow/approval/{taskId}/{approver}/{approveOper}/{applyId}")
    public Result<String> approval(@ApiParam("任务ID") @PathVariable("taskId") String taskId
            , @ApiParam("审批人") @PathVariable("approver") String approver
//            ,@ApiParam("标识 1-部门领导审批、2-办公室主任审批、3-档案管理员审批") @PathVariable("flag") String flag
            , @ApiParam("审批操作 'true'  'false'") @PathVariable("approveOper") String approveOper
            , @ApiParam("申请ID") @PathVariable("applyId") String applyId
            , @ApiParam("审批意见") @RequestParam(value = "opinion", required = false) String opinion
            , HttpServletRequest request
    ) {


        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String taskKey = task.getTaskDefinitionKey();


        UseBorrowRecord uba = useBorrowRecordMapper.selectById(applyId);
        String nextApprover = "";
        String instanceid = "";
        String postCode = "";
        instanceid = uba.getProcessId();

//        //获取历史记录
//        List<HistoricActivityInstance> his = histiryService.createHistoricActivityInstanceQuery()
//                .processInstanceId(instanceid).activityType("userTask").orderByHistoricActivityInstanceStartTime().asc().list();
//        String upApprover = "";
//        //获取上一个审批人用户名
//        if(null != his && his.size()-2 >=0){
//            upApprover = his.get(his.size()-2).getAssignee();
//        }
//        System.err.println("上一个审批人用户名："+upApprover);
//        //获取上一个审批人信息  设置为已办
//        //已办
//        BaseTask bt = EkpHttpWsUtil.borrowEkpDone(instanceid,upApprover);

        ProcessDetails pd = new ProcessDetails();
        pd.setApprover(approver);
        pd.setProcessName(taskKey);
        pd.setApprovalOpinion(opinion);
        pd.setApprovalStatus(approveOper);
        pd.setApprovalTime(DateUtil.getCurrentTime());
        pd.setProcessId(instanceid);
        pd.setUserId(uba.getUserId().toString());
        processDetailsMapper.insert(pd);


        BaseUser baseUser= userMapper.selectOne(new QueryWrapper<BaseUser>().eq("username",approver));

        UserInfo loginUser=new UserInfo();
        loginUser.setId(baseUser.getId());
        loginUser.setRealName(baseUser.getRealName());
        loginUser.setFondsId(uba.getFondsId());
        String approveNodeCode=BehaveLogType.DEPT_AUDIT.getKey();
        String approveNode=BehaveLogType.DEPT_AUDIT.getValue();
        if (taskKey.equals("officeLeaderAudit")) {
            approveNodeCode=BehaveLogType.OFFICE_AUDIT.getKey();
            approveNode=BehaveLogType.OFFICE_AUDIT.getValue();

        }else if(taskKey.equals("archivistLeaderAudit")){
            approveNodeCode=BehaveLogType.ARCHIVIST_AUDIT.getKey();
            approveNode=BehaveLogType.ARCHIVIST_AUDIT.getValue();
        }
        String approveFlag="审批通过";
        if("false".equals(approveOper)){
            approveFlag="审批不通过";
        }
        String description= approveFlag+"，审批意见："+opinion;

        Map<String, Object> variables = new HashMap<String, Object>();

        //最终审批
        if (taskKey.equals("archivistLeaderAudit")) {
//        if (flag.equals("3")){
            //档案管理员审批
            variables.put("archivistLeader", approver);
            variables.put("archivistLeaderApprove", approveOper);
            taskService.claim(taskId, approver);
            taskService.complete(taskId, variables);


            if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
                //已办
                BaseTask bt = EkpHttpWsUtil.borrowEkpDone(instanceid, approver);

                QueryWrapper<Post> postQueryWrapper=new QueryWrapper<>();
                postQueryWrapper.eq("code","archivistLeader");
                Post post= postMapper.selectOne(postQueryWrapper);
                acceptService.receiveFlow(instanceid,post.getId().toString(),post.getName(),approver,DateUtil.getCurrentTime());
                acceptService.updateFlow(instanceid,post.getId().toString(),post.getName(),approver,DateUtil.getCurrentTime(),"2");
            }

            if (approveOper.equals("true")) {
                if (uba.getAuthType().equals("2")) {
                    uba.setState("3");
                } else {
                    uba.setState("2");
                }
                uba.setStartTime(DateUtil.getCurrentTime());
                LocalDate ld = LocalDate.now().plusDays(Long.parseLong(uba.getBDays()));
                uba.setEndTime(ld.format(DateTimeFormatter.ofPattern(DateUtil.DateFormat.YYYY_MM_DD.getValue())));

            } else {
                uba.setState("1");
                uba.setRemark(opinion);
            }
            useBorrowRecordMapper.updateById(uba);

            archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(uba.getFileId().toString(),approveNodeCode,approveNode,description),loginUser ,request);

            return ResultUtil.success();
        }


        //获取公司下的所有部门ID
        List<Long> deptIds = new ArrayList();
        List<UserDept> userDeptList = userDeptMapper.selectList(new QueryWrapper<UserDept>().eq("userId", uba.getUserId()));
        Dept dept = deptMapper.selectById(userDeptList.get(0).getDeptId());
        String p = dept.getPids().substring(dept.getPids().indexOf("/") + 1);
        String companyCode = p.substring(0, p.indexOf("/"));

        List<Dept> deptList = deptMapper.selectList(new QueryWrapper<Dept>().like("pids", companyCode));
        deptList.forEach((Dept d) -> {
            deptIds.add(d.getId());
        });


        if (taskKey.equals("deptLeaderAudit")) {
            //部门领导审批
            postCode = "officeLeader";

            Map<String, Object> param = new HashMap<>();
            param.put("postCode", postCode);
            param.put("deptIds", deptIds);
            List<BaseUser> userList = userService.gainDeptPostUser(param);
            if (!BaseUtil.listIsNotNullElement(userList)) {
                return ResultUtil.error("没有找到对应的审核人");
            }
            nextApprover = userList.get(0).getUsername();


            variables.put("officeLeader", nextApprover);
            variables.put("deptLeaderApprove", approveOper);//true || false

            if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
                QueryWrapper<Post> postQueryWrapper=new QueryWrapper<>();
                postQueryWrapper.eq("code","deptLeader");
                Post post= postMapper.selectOne(postQueryWrapper);
                acceptService.receiveFlow(instanceid,post.getId().toString(),post.getName(),approver,DateUtil.getCurrentTime());
                acceptService.updateFlow(instanceid,post.getId().toString(),post.getName(),approver,DateUtil.getCurrentTime(),"1");
            }


        } else if (taskKey.equals("officeLeaderAudit")) {
            //办公室主任审批
            postCode = "archivistLeader";

            Map<String, Object> param = new HashMap<>();
            param.put("postCode", postCode);
            param.put("deptIds", deptIds);
            List<BaseUser> userList = userService.gainDeptPostUser(param);
            if (!BaseUtil.listIsNotNullElement(userList)) {
                return ResultUtil.error("没有找到对应的审核人");
            }
            nextApprover = userList.get(0).getUsername();


            variables.put("archivistLeader", nextApprover);
            variables.put("officeLeaderApprove", approveOper);

            if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
                QueryWrapper<Post> postQueryWrapper=new QueryWrapper<>();
                postQueryWrapper.eq("code","officeLeader");
                Post post= postMapper.selectOne(postQueryWrapper);
                acceptService.receiveFlow(instanceid,post.getId().toString(),post.getName(),approver,DateUtil.getCurrentTime());
                acceptService.updateFlow(instanceid,post.getId().toString(),post.getName(),approver,DateUtil.getCurrentTime(),"1");
            }


        } else {
            return ResultUtil.error("请核实流程");
        }

        if (approveOper.equals("false")) {
            uba.setState("1");
            uba.setRemark(opinion);
        }
        useBorrowRecordMapper.updateById(uba);

        taskService.claim(taskId, approver);
        taskService.complete(taskId, variables);

        if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
            //已办
            BaseTask bt = EkpHttpWsUtil.borrowEkpDone(instanceid, approver);
            if (null != bt) baseTaskMapper.insert(bt);

            //待办
            BaseTask bt2 = EkpHttpWsUtil.borrowEkp(instanceid, nextApprover, uba.getId());
            if (null != bt2) baseTaskMapper.insert(bt2);
        }

        archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(uba.getFileId().toString(),approveNodeCode,approveNode,description),loginUser ,request);

        return ResultUtil.success();

    }


//    @ApiOperation(value = "获取部门领导审批待办列表", notes = "")
//    @GetMapping("/borrow/deptTaskList")
//    public Result<List<UseBorrowRecord>> deptTaskList(@RequestParam("username") String username,
//                                                     @ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
//                                                     @ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize) {
//        List<UseBorrowRecord> result = new ArrayList<>();
//        int firstrow = (pageNum - 1) * pageSize;
//
//        // 使用任务候选人查询待办列表
//        List<Task> tasks= taskService.createTaskQuery().taskAssignee(username).taskName("部门领导审批").listPage(firstrow, pageNum);
//        for(Task task:tasks){
//            String instanceid=task.getProcessInstanceId();
//            ProcessInstance ins= runtimeService.createProcessInstanceQuery().processInstanceId(instanceid).singleResult();
//            String businesskey = ins.getBusinessKey();
//            // 使用业务号查出业务数据一起返回
//            UseBorrowRecord a = useBorrowRecordMapper.selectById(Integer.parseInt(businesskey));
//            a.setTaskId(task.getId());
//            a.setTaskName(task.getName());
//            a.setProcessinstanceId(task.getProcessInstanceId());
//            a.setProcessdefId(task.getProcessDefinitionId());
//            a.setTaskCreateTime(task.getCreateTime());
//            result.add(a);
//        }
//
//        return ResultUtil.success(result);

//    }


//    @ApiOperation(value = "借阅部门领导审批", notes = "")
//    @PostMapping("/borrow/deptApproval/{taskid}/{approver}/{deptApprove}")
//    public Result<String> deptApproval(@PathVariable("taskid") String taskid,@PathVariable("approver") String approver,@PathVariable("deptApprove") String deptApprove) {
//        String deptApproval = "";
//
//        Map<String, Object> variables = new HashMap<String, Object>();
//        //办公室主任用户名
//        variables.put("officeLeader", approver);
//        variables.put("deptLeaderApprove", deptApprove);//true || false
//        taskService.claim(taskid, approver);
//        taskService.complete(taskid, variables);
//
//        return ResultUtil.success();
//
//    }

//    @ApiOperation(value = "借阅办公室主任审批", notes = "")
//    @PostMapping("/borrow/officeDirectorApproval/{taskid}/{username}/{officeApprove}")
//    public Result<String> officeDirectorApproval(@PathVariable("taskid") String taskid,@PathVariable("username") String username,@PathVariable("officeApprove") String officeApprove) {
//
//        Map<String, Object> variables = new HashMap<String, Object>();
//        //办公室主任用户名
//        variables.put("officeLeaderApprove", officeApprove);
//        variables.put("officeLeader", "admin");
//        taskService.claim(taskid, username);
//        taskService.complete(taskid, variables);
//
//        return ResultUtil.success();
//
//    }

//    @ApiOperation(value = "借阅档案管理员审批", notes = "")
//    @PostMapping("/borrow/officeDirectorApproval/{taskid}/{username}/{archivistApprove}")
//    public Result<String> archivistApproval(@PathVariable("taskid") String taskid,@PathVariable("username") String username,@PathVariable("archivistApprove") String archivistApprove) {
//
//        Map<String, Object> variables = new HashMap<String, Object>();
//        variables.put("archivistLeaderApprove", archivistApprove);
//        variables.put("archivistLeader", "admin");
//        taskService.claim(taskid, username);
//        taskService.complete(taskid, variables);
//
//        return ResultUtil.success();
//
//    }


    @ApiOperation(value = "我的下载", notes = "")
    @PostMapping("/downLog")
    public Result<PageInfo<UseUserRecordLog>> downLog(@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                                      @ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                                      HttpServletRequest request) {
        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        QueryWrapper<UseUserRecordLog> queryWrapper = new QueryWrapper<UseUserRecordLog>();
        Page<UseUserRecordLog> page = new Page<>(pageNum == null ? 0 : pageNum, pageSize == null ? 10 : pageSize);
        queryWrapper.eq("userId", loginInfo.getId());
        queryWrapper.eq("recordLogType", "1");
        IPage<UseUserRecordLog> info = useUserRecordLogMapper.selectPage(page, queryWrapper);
        PageInfo<UseUserRecordLog> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", data);
    }

    @ApiOperation(value = "删除我的下载", notes = "")
    @DeleteMapping("/downLog/{id}")
    public Result<String> downLog(@PathVariable("id") String id,
                                  HttpServletRequest request) {
        useUserRecordLogMapper.deleteById(id);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }

    @ApiOperation(value = "我的预览", notes = "")
    @PostMapping("/preview")
    public Result<PageInfo<UseUserRecordLog>> previewLog(@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                                         @ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                                         @ApiParam("") @RequestParam(value = "startTime", required = false) String startTime,
                                                         @ApiParam("") @RequestParam(value = "endTime", required = false) String endTime,
                                                         HttpServletRequest request) {
        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        QueryWrapper<UseUserRecordLog> queryWrapper = new QueryWrapper<UseUserRecordLog>();
        Page<UseUserRecordLog> page = new Page<>(pageNum == null ? 0 : pageNum, pageSize == null ? 10 : pageSize);
        queryWrapper.eq("userId", loginInfo.getId());
        queryWrapper.eq("recordLogType", "1");
        IPage<UseUserRecordLog> info = useUserRecordLogMapper.selectPage(page, queryWrapper);
        PageInfo<UseUserRecordLog> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", data);
    }


    @ApiOperation(value = "我的预览删除", notes = "")
    @DeleteMapping("/preview/{id}")
    public Result<String> previewLog(@PathVariable("id") String id,
                                     HttpServletRequest request) {
        useUserRecordLogMapper.deleteById(id);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }


    @ApiOperation(value = "文件预览", notes = "")
    @GetMapping("/file/{id}")
    public Result<ArchivesDetails> fileDetails(@PathVariable String id,
                                               HttpServletRequest request) {
        ArchivesDoc archivesDoc = archivesDocMapper.selectById(id);
        if (archivesDoc == null) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件信息查找不到", null);
        }
        return docService.useDetails(archivesDoc, request);
        //return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),"",null);
    }


    @ApiOperation(value = "文件下载记录", notes = "")
    @GetMapping("/file/down/{id}")
    public Result<ArchivesDetails> fileDown(@PathVariable String id,
                                            HttpServletRequest request) {
		/*ArchivesDoc archivesDoc = archivesDocMapper.selectById(id);
		if (archivesDoc == null) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件信息查找不到", null);
		}
		return docService.details(archivesDoc);*/
        //useUserRecordLogMapper
        //return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),"",null);
        return null;
    }


    @ApiOperation(value = "是否可阅览", notes = "")
    @GetMapping("/isRead/{id}")
    @LoginAuth()
    public Result<Boolean> isRead(@PathVariable("id") String id, @ApiIgnore @LoginUser UserInfo loginUser) {
        UseBorrowRecord ubr = useBorrowRecordMapper.selectById(id);

        String startTime = ubr.getStartTime();
        String endTime = ubr.getEndTime();
        String currentTime = DateUtil.getCurrentTime(DateUtil.DateFormat.YYYY_MM_DD);

        if (currentTime.compareTo(endTime) >= 0) {
            ubr.setState("3");
            useBorrowRecordMapper.updateById(ubr);
            return ResultUtil.success(false);
        }

        return ResultUtil.success(true);

    }


    //======================================================
    //=================借阅全宗   start=====================
    //======================================================

    @ApiOperation(value = "是否可借阅（全宗）", notes = "")
    @PostMapping("/borrow/fongds/isBorrow")
    @LoginAuth()
    public Result<UseBorrowFondsRecord> isBorrow(@ApiIgnore @LoginUser UserInfo loginUser) {

        Dept dept = deptMapper.selectById("90000");

        QueryWrapper<UseBorrowFondsRecord> qw = new QueryWrapper();
        qw.eq("fondsId", dept.getFondsId());
        qw.eq("userId", loginUser.getId());
//        qw.eq("state","2");
        UseBorrowFondsRecord useBorrowFondsRecord = useBorrowFondsRecordMapper.selectOne(qw);

        return ResultUtil.success(useBorrowFondsRecord);


    }


    @ApiOperation(value = "借阅（全宗）申请", notes = "")
    @PostMapping("/borrow/fongds/apply")
    @LoginAuth()
    @Transactional(rollbackFor = Exception.class)
    public Result<String> fongdsApply(@RequestBody UseBorrowFondsRecord useBorrowFondsRecord,
                                      @ApiIgnore @LoginUser UserInfo loginUser) {

        Dept dept = deptMapper.selectById("90000");
        QueryWrapper<UseBorrowFondsRecord> qw = new QueryWrapper();
        qw.eq("fondsId", dept.getFondsId());
        qw.eq("userId", loginUser.getId());
        useBorrowFondsRecordMapper.delete(qw);


        useBorrowFondsRecord.setUserId(loginUser.getId());
        useBorrowFondsRecord.setCreateBy(loginUser.getRealName());
        useBorrowFondsRecord.setCreateTime(LocalDateTimeUtil.getNowTimeYMDMS());
        useBorrowFondsRecord.setState("0");


        useBorrowFondsRecord.setFondsId(dept.getFondsId().toString());

        // 获取日期
        Date date1 = MyDateUtil.parseDate(useBorrowFondsRecord.getStartTime(), "yyyy-MM-dd");

        int addDayNum = 7;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);
        //增加7天
        cal.add(Calendar.DAY_OF_MONTH, addDayNum);
        Date date2 = cal.getTime();
        useBorrowFondsRecord.setEndTime(DateUtil.getFormatDate(date2, DateUtil.DateFormat.YYYY_MM_DD));


        useBorrowFondsRecord.setBDays(addDayNum + "");
        int i = useBorrowFondsRecordMapper.insert(useBorrowFondsRecord);
        if (i < 1) return ResultUtil.error();


        String modelId = IdUtil.simpleUUID();
        String modelName = "借阅全宗申请";
        String approver = "testUser";//审批人

//        //        //发送代办审核
//        EkpReplaceDisposeDto dto = new EkpReplaceDisposeDto();
//        dto.setLoginName(approver);//审批人
//        dto.setModelId(modelId);
//        dto.setModelName(modelName);
//        dto.setSubject(modelName + "审批");
//        dto.setType(1);
//        Result r = EkpHttpWsUtil.sendTodo(dto);
        Result r = ResultUtil.success();

        //增加审核信息
        EkpRecord ekp = new EkpRecord();
        ekp.setModelId(modelId);
        ekp.setModelName(modelName);
        ekp.setCreateTime(DateUtil.getCurrentTime());
        ekp.setCreateBy(loginUser.getUsername());
        ekp.setApprover(approver);
        ekp.setState("0");
        ekp.setOper(r.getCode());
//        ekp.setRespMessage(r.getMsg());
//        ekp.setRequMessage(r.getData().toString());
        ekp.setRequestNum(1);
        ekp.setDataId(useBorrowFondsRecord.getId().toString());

        ekpRecordMapper.insert(ekp);


        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }


    @ApiOperation(value = "借阅全宗申请列表", notes = "")
    @GetMapping("/borrow/fongds")
    public Result<PageInfo<UseBorrowFondsRecord>> borrowFongdsList(@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                                                   @ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                                                   @ApiParam("借阅开始时间") @RequestParam(value = "startTime", required = false) String startTime,
                                                                   @ApiParam("借阅结束时间") @RequestParam(value = "endTime", required = false) String endTime,
                                                                   @ApiParam("全宗ID") @RequestParam(value = "fondsId", required = false) String fondsId,
                                                                   @ApiIgnore @LoginUser UserInfo loginUser) {

        Page<UseBorrowFondsRecord> page = new Page<>(pageNum == null ? 0 : pageNum, pageSize == null ? 10 : pageSize);
        QueryWrapper<UseBorrowFondsRecord> queryWrapper = new QueryWrapper<>();


        if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
            queryWrapper.gt("starTime", startTime);
            queryWrapper.lt("endTime", endTime);

        }
        queryWrapper.eq("userId", loginUser.getId());
        IPage<UseBorrowFondsRecord> info = useBorrowFondsRecordMapper.selectPage(page, queryWrapper);

        info.getRecords().forEach((UseBorrowFondsRecord ubfr) -> {
            ArchivesFonds af = archivesFondsMapper.selectById(ubfr.getFondsId());
            ubfr.setFondsName(af.getFondsName());
        });


        PageInfo<UseBorrowFondsRecord> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", data);
    }


    //======================================================
    //=================借阅全宗   end=====================
    //======================================================


    @ApiOperation("使用流程实例编号获取历史流程数据")
    @RequestMapping(value = "/processinfo", method = RequestMethod.POST)
    @ResponseBody
    public List<HistoricActivityInstance> processinfo(@RequestParam("instanceid") String instanceid) {
        List<HistoricActivityInstance> his = histiryService.createHistoricActivityInstanceQuery()
                .processInstanceId(instanceid).activityType("userTask").orderByHistoricActivityInstanceStartTime().asc().list();
        return his;
    }

//    public static void main(String[] args) {
//        String a =;
//        String[] split = a.split(",");
//        String s = "typeNum.classNum-archivalNum+dossierNum.secret";
//        System.out.println(split[1]);
//        for (int i = 0; i < split.length; i++) {
//            String[] split1 = s.split(split[i]);
//            String[] split2 = split1[1].split(split[i]);
//        }
//
//
//    }
    public static void main(String[] args) {
        String str = "typeNum.classNum-archivalNum+dossierNum.secret";
        char[] separators = new char[]{'.', '-', '+', '.'};

        String[] parts = splitStringByChars(str, separators);
        for (String part : parts) {
            System.out.println(part);
        }
    }

    public static String[] splitStringByChars(String str, char[] chars) {
        String regex = "[" + Pattern.quote(String.valueOf(chars)) + "]";
        System.out.println(regex);
        return str.split(regex);
    }

}
